<?php

declare(strict_types=1);

namespace App\Exception\Handler;

use Aether\AetherResponse;
use Aether\RpcException\BusinessException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class BusinessExceptionHandler extends ExceptionHandler
{
    /**
     * 显式声明next属性，确保存在.
     */
    protected ?self $next = null;

    /**
     * 处理异常.
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 只处理BusinessException类型的异常
        if ($throwable instanceof BusinessException) {
            $result = AetherResponse::error(
                $throwable->getCode(),
                $throwable->getMessage() ?: '业务处理异常'
            );

            $body = json_encode($result, JSON_UNESCAPED_UNICODE);

            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(200)
                ->withBody(new SwooleStream((string) $body));
        }

        // 安全处理下一个处理器
        if ($this->next !== null) {
            return $this->next->handle($throwable, $response);
        }

        // 如果没有下一个处理器，直接返回原始响应
        return $response;
    }

    /**
     * 判断是否需要处理该异常.
     */
    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof BusinessException;
    }

    /**
     * 显式实现setNext方法.
     */
    public function setNext(self $handler): void
    {
        $this->next = $handler;
    }
}
